package com.example.javabase.tools;


import com.example.javabase.entity.WorkTaskRegisterDto;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class RecursionUtils {

    public static void main(String[] args) {

    }

    //建立树形结构
    public List<WorkTaskRegisterDto> buildTree(List<WorkTaskRegisterDto> departList) {
        List<WorkTaskRegisterDto> treeMenus = new ArrayList<>();
        for (WorkTaskRegisterDto menuNode : getRootNode(departList)) {
            buildChildTree(departList, menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private WorkTaskRegisterDto buildChildTree(List<WorkTaskRegisterDto> departList, WorkTaskRegisterDto pNode) {
        List<WorkTaskRegisterDto> childDepart = new ArrayList<>();
        for (WorkTaskRegisterDto menuNode : departList) {
            if (!StringUtils.isEmpty(menuNode.getParentId()) && menuNode.getParentId().equals(pNode.getId())) {
                childDepart.add(buildChildTree(departList, menuNode));
            }
        }
        pNode.setChildren(childDepart);
        return pNode;
    }

    //获取根节点
    private List<WorkTaskRegisterDto> getRootNode(List<WorkTaskRegisterDto> departList) {
        List<WorkTaskRegisterDto> rootMenuLists = new ArrayList<>();
        for (WorkTaskRegisterDto menuNode : departList) {
            if (StringUtils.isEmpty(menuNode.getParentId())) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

}
